package com.sendtion.xrichtextdemo.comm;

import com.bumptech.glide.request.target.ImageViewTarget;

import ohos.agp.components.DependentLayout;
import ohos.agp.components.Image;
import ohos.media.image.PixelMap;

import org.jetbrains.annotations.Nullable;

/**
 * Glide加载图片时，根据图片宽度等比缩放
 *
 * @since 2021-06-22
 */
public class TransformationScale extends ImageViewTarget<PixelMap> {
    private static final double DOUBLE = 0.1;
    private static final int INT = 10;
    private Image target;

    /**
     * TransformationScale
     *
     * @param target
     */
    public TransformationScale(Image target) {
        super(target);
        this.target = target;
    }

    @Override
    protected void setResource(@Nullable PixelMap resource) {
        view.setPixelMap(resource);

        if (resource != null) {
            int width = resource.getImageInfo().size.width;
            int height = resource.getImageInfo().size.height;

            int imageViewWidth = target.getWidth();

            float sy = (float) (imageViewWidth * DOUBLE) / (float) (width * DOUBLE);

            int imageHeight = (int) (height * sy);
            DependentLayout.LayoutConfig params = new DependentLayout.LayoutConfig(
                    DependentLayout.LayoutConfig.MATCH_PARENT, imageHeight);
            params.setMarginBottom(INT);
            target.setLayoutConfig(params);
        }
    }
}